<?php
declare (strict_types = 1);

namespace app\model;

use think\Model;
use think\model\concern\SoftDelete;

/**
 * 管理员模型
 * Class Admin
 * @package app\model
 */
class Admin extends Model
{
    // 表名
    protected $name = 'admins';
    
    // 自动时间戳
    protected $autoWriteTimestamp = true;
    
    // 字段类型转换
    protected $type = [
        'id' => 'integer',
        'status' => 'integer',
        'last_login_time' => 'datetime',
        'token_expire_time' => 'datetime',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];
    
    // 隐藏字段
    protected $hidden = ['password', 'token'];
    
    // 字段自动完成
    protected $auto = [];
    protected $insert = [];
    protected $update = [];
    
    /**
     * 密码修改器
     * @param $value
     * @return string
     */
    public function setPasswordAttr($value)
    {
        return password_hash($value, PASSWORD_DEFAULT);
    }
    
    /**
     * 状态获取器
     * @param $value
     * @return string
     */
    public function getStatusTextAttr($value, $data)
    {
        $status = [0 => '禁用', 1 => '启用'];
        return $status[$data['status']] ?? '未知';
    }
    
    /**
     * 关联角色
     * @return \think\model\relation\BelongsToMany
     */
    public function roles()
    {
        return $this->belongsToMany(Role::class, AdminRole::class,'role_id', 'admin_id');
    }
    
    /**
     * 验证密码
     * @param string $password
     * @return bool
     */
    public function checkPassword(string $password): bool
    {
        return password_verify($password, $this->password);
    }
    
    /**
     * 获取管理员权限
     * @return array
     */
    public function getPermissions(): array
    {
        // 获取管理员角色
        $roles = $this->roles()->select();
        
        // 检查是否有超级管理员角色（ID为1）
        foreach ($roles as $role) {
            if ($role->id === 1) {
                // 如果是超级管理员，直接返回所有权限的code
                return Permission::where('status', 1)->column('code');
            }
        }
        
        // 获取所有角色的权限
        $permissions = [];
        foreach ($roles as $role) {
            // 获取角色的权限ID
            $permissionIds = $role->getPermissionIds();
            
            // 获取权限详情
            if (!empty($permissionIds)) {
                $rolePermissions = Permission::where('id', 'in', $permissionIds)
                    ->where('status', 1)
                    ->column('code');
                $permissions = array_merge($permissions, $rolePermissions);
            }
        }
        
        // 去重返回
        return array_unique($permissions);
    }
    
    /**
     * 获取管理员菜单
     * @return array
     */
    public function getMenus(): array
    {
        $menus = [];
        
        // 如果角色已经预加载，使用预加载的数据
        if (isset($this->data['roles'])) {
            $roles = $this->roles;
        } else {
            $roles = $this->roles()->select();
        }
        
        foreach ($roles as $role) {
            // 如果权限已经预加载，使用预加载的数据并过滤菜单类型和状态
            if (isset($role->data['permissions'])) {
                $rolePermissions = array_filter($role->permissions->toArray(), function($permission) {
                    return $permission['type'] === 'menu' && $permission['status'] == 1;
                });
            } else {
                $rolePermissions = $role->permissions()->where('type', 'menu')->where('status', 1)->select();
            }
            
            foreach ($rolePermissions as $permission) {
                // 处理数组和对象两种情况
                if (is_array($permission)) {
                    $menus[] = [
                        'id' => $permission['id'],
                        'name' => $permission['name'],
                        'title' => $permission['name'], // 添加title字段兼容前端
                        'code' => $permission['code'],
                        'path' => $permission['path'],
                        'component' => $permission['component'],
                        'icon' => $permission['icon'],
                        'parent_id' => $permission['parent_id'],
                        'sort' => $permission['sort'],
                    ];
                } else {
                    $menus[] = [
                        'id' => $permission->id,
                        'name' => $permission->name,
                        'title' => $permission->name, // 添加title字段兼容前端
                        'code' => $permission->code,
                        'path' => $permission->path,
                        'component' => $permission->component,
                        'icon' => $permission->icon,
                        'parent_id' => $permission->parent_id,
                        'sort' => $permission->sort,
                    ];
                }
            }
        }
        
        // 去重并按sort排序
        $menus = array_unique($menus, SORT_REGULAR);
        usort($menus, function($a, $b) {
            return $a['sort'] - $b['sort'];
        });
        
        return $this->buildMenuTree($menus);
    }
    
    /**
     * 构建菜单树
     * @param array $menus
     * @param int $parentId
     * @return array
     */
    private function buildMenuTree(array $menus, int $parentId = 0): array
    {
        $tree = [];
        foreach ($menus as $menu) {
            if ($menu['parent_id'] == $parentId) {
                $children = $this->buildMenuTree($menus, $menu['id']);
                if ($children) {
                    $menu['children'] = $children;
                }
                $tree[] = $menu;
            }
        }
        return $tree;
    }
}